<script>
//导入用户的网络请求API
import userApi from '@/req/user.js'
import {ElMessage} from "element-plus";
export default {
  name: "TestAxios",
  methods:{
    login(){
      //获取用户的账户和密码
      //模拟数据
      let formData = new FormData();
      formData.append("username","jack");
      formData.append("password","123456");

      userApi.login(formData).then(res=>{
        console.log(res)
        //判断业务码
        if (res.code===20000){
          ElMessage({
            type:'success',
            message:'登录成功',
            onClose:()=>{
              //跳转到主页面
            }
          })
          //将token存储在本地
          localStorage.setItem("token",res.data);
        }else{
          //失败
        }
      }).catch(error=>{
        console.log(error);
      })
    },
    query(){
      let username = "jack"
      userApi.getUser(username).then(res=>{
        console.log(res);
        if (res.code===60001){
          ElMessage({
            message: res.message,
            type:'error',
          })
        }

      }).catch(error=>{
        console.log(error)
      })
    },
    getUserInfo(){
      userApi.getUserInfo('tom').then(res=>{
          if (res.code===20000){
            ElMessage({
              type:'success',
              message:'查询用户信息成功'
            })
            //获取数据操作
          }else{
            ElMessage({
              type:'error',
              message:res.message
            })
          }
      }).catch(error=>{
        console.log(error)
      })
    },
    getOrders(){
      userApi.getOrders().then(res=>{
        console.log(res)
        if (res.code===20000){
          ElMessage({
            type: 'success',
            message: '查询用户订单信息成功'
          })
        }else if(res.code===60001){
          ElMessage({
            type: 'error',
            message: '查看订单,请先登录',
            onClose:()=>{
              //去登录
              this.$router.push('/login')
            }
          })
        }else if (res.code ===50004){
          ElMessage({
            type: 'error',
            message: '你暂时没有订单'
          })
        }
      }).catch(error=>{
        console.log(error)
      })
    }
  }
}
</script>

<template>
  <h3>这是测试axios的页面</h3>
  <el-button @click="this.$router.go(-1)">返回</el-button>
  <hr>
  <el-space :size="50">
    <el-button @click="login" type="primary" size="large">登录</el-button>
    <el-tooltip
        class="box-item"
        effect="dark"
        content="使用问号传递参数"
        placement="top-start"
    >
      <el-button type="primary" @click="query">查询用户信息1</el-button>
    </el-tooltip>
    <el-tooltip
        class="box-item"
        effect="dark"
        content="使用restful风格传递参数"
        placement="top-start"
    >
      <el-button type="primary" @click="getUserInfo">查询用户信息2</el-button>
    </el-tooltip>
    <el-button type="primary" size="large" @click="getOrders">查询订单</el-button>
  </el-space>
</template>

<style scoped>

</style>